package com.hbnu.zhanglian.server;

import java.io.*;
import java.net.*;
import java.util.*;

public class GameServer {
    private static final int PORT = 8888;
    private static List<ClientHandler> clients = new ArrayList<>();
    private static String currentWord = "";
    private static boolean gameStarted = false;
    private static int roundCount = 0;
    private static final int MAX_ROUNDS = 3;
    private static String[] words = {"苹果", "太阳", "小猫", "汽车", "房子", "大树", "花朵", "书包", "电脑", "手机"};
    private static List<String> usedWords = new ArrayList<>(); // 记录已使用的词语

    public static void main(String[] args) {
        System.out.println("你画我猜游戏服务器启动...");
        try (ServerSocket serverSocket = new ServerSocket(PORT)) {
            System.out.println("服务器监听端口: " + PORT);

            while (true) {
                Socket clientSocket = serverSocket.accept();
                ClientHandler client = new ClientHandler(clientSocket);
                clients.add(client);
                new Thread(client).start();

                System.out.println("新客户端连接，当前客户端数: " + clients.size());

                // 当有2个玩家时自动开始游戏
                if (clients.size() == 2 && !gameStarted) {
                    roundCount = 0; // 重置轮次计数
                    usedWords.clear(); // 清空已使用词语
                    startNewGame();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 向所有客户端广播消息
    public static void broadcast(String message) {
        for (ClientHandler client : clients) {
            client.sendMessage(message);
        }
    }

    // 获取随机不重复的词语
    public static String getRandomWord() {
        if (usedWords.size() >= words.length) {
            // 如果所有词语都用过了，重新开始
            usedWords.clear();
        }

        String word;
        do {
            word = words[(int)(Math.random() * words.length)];
        } while (usedWords.contains(word)); // 确保不重复

        usedWords.add(word);
        return word;
    }

    // 开始新游戏
    public static void startNewGame() {
        if (roundCount >= MAX_ROUNDS) {
            endGameSession();
            return;
        }

        gameStarted = true;
        roundCount++;
        currentWord = getRandomWord(); // 使用不重复的词语

        System.out.println(" 第 " + roundCount + " 轮游戏开始，词语: " + currentWord);
        System.out.println("已使用词语: " + usedWords);
        broadcast("==================================");
        broadcast(" 第 " + roundCount + " 轮游戏开始！");
        broadcast(" 系统题目: " + getWordDescription(currentWord));
        broadcast(" 请输入你的猜测");
        broadcast("==================================");
    }

    // 获取词语描述
    public static String getWordDescription(String word) {
        switch (word) {
            case "苹果": return "红色的圆形水果，吃起来甜甜的";
            case "太阳": return "白天出现在天空，给我们光和热";
            case "小猫": return "可爱的宠物，会喵喵叫，抓老鼠";
            case "汽车": return "四个轮子的交通工具，可以载人";
            case "房子": return "人们居住的地方，有屋顶和门窗";
            case "大树": return "高高的植物，有树干和树叶";
            case "花朵": return "美丽的植物，有各种颜色和香味";
            case "书包": return "学生用来装书本的袋子";
            case "电脑": return "可以上网、打字的电子设备";
            case "手机": return "可以打电话、发短信的便携设备";
            default: return word;
        }
    }

    // 处理猜词
    public static void handleGuess(String guess, ClientHandler guesser) {
        if (guess.equalsIgnoreCase(currentWord)) {
            broadcast(guesser.getUsername() + " 猜对了！答案是: " + currentWord);
            broadcast(roundCount + " 轮游戏结束");

            // 延迟后开始下一轮或结束游戏
            new Timer().schedule(new TimerTask() {
                public void run() {
                    if (clients.size() == 2) {
                        startNewGame();
                    }
                }
            }, 3000);
        } else {
            broadcast(guesser.getUsername() + " 猜: " + guess);
            guesser.sendMessage(" 猜错了，再试试！");
        }
    }

    // 结束游戏会话
    public static void endGameSession() {
        broadcast("==================================");
        broadcast(" 游戏结束！共完成了 " + MAX_ROUNDS + " 轮游戏");
        broadcast(" 本轮游戏使用的词语: " + String.join("、", usedWords));
        broadcast(" 感谢参与！");
        broadcast(" 可以重新登录开始新的游戏会话");
        broadcast("==================================");

        gameStarted = false;
        roundCount = 0;
        currentWord = "";
        usedWords.clear(); // 清空已使用词语

        // 断开所有客户端连接
        for (ClientHandler client : clients) {
            try {
                client.socket.close();
            } catch (IOException e) {
                // 忽略关闭异常
            }
        }
        clients.clear();
    }

    static class ClientHandler implements Runnable {
        public Socket socket;
        private BufferedReader in;
        private PrintWriter out;
        private String username;

        public ClientHandler(Socket socket) {
            this.socket = socket;
        }

        public String getUsername() {
            return username;
        }

        public void sendMessage(String message) {
            if (out != null) {
                out.println(message);
            }
        }

        @Override
        public void run() {
            try {
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                out = new PrintWriter(socket.getOutputStream(), true);

                // 登录
                out.println("=== 欢迎来到你画我猜游戏 ===");
                out.println("请输入你的用户名:");
                username = in.readLine();

                out.println(" 登录成功！欢迎 " + username);
                broadcast(username + " 加入了游戏");

                out.println(" 等待其他玩家加入...");
                out.println("当有2名玩家时游戏将自动开始");
                out.println(" 本次游戏共进行 " + MAX_ROUNDS + " 轮");
                //out.println(" 每轮题目都不会重复");
                out.println("==================================");

                // 如果已经有2个玩家，立即开始游戏
                if (clients.size() == 2 && !gameStarted) {
                    startNewGame();
                }

                String message;
                while ((message = in.readLine()) != null) {
                    if (gameStarted) {
                        handleGuess(message, this);
                    }
                }
            } catch (IOException e) {
                System.out.println("客户端断开连接: " + username);
            } finally {
                clients.remove(this);
                if (username != null) {
                    broadcast(username + " 离开了游戏");
                }
                try {
                    socket.close();
                } catch (IOException e) {}
            }
        }
    }
}